<!--销售订单-->
<template>
    <el-form :model="saleform" ref="saleref" :inline="true" style="text-align: left;">
        <el-form-item label="销售单号:" prop="code">
            <el-input placeholder="请输入" v-model="saleform.code"></el-input>
        </el-form-item>
        <el-form-item label="单据状态" prop="ordstatus">
            <el-select placeholder="请选择" style="width:200px" v-model="saleform.ordstatus">
                <el-option v-for="item in status" :key="item.dict_value" :label="item.dict_label" :value="item.dict_value"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="客户名称" prop="cust">
            <el-select placeholder="请选择" style="width:200px" v-model="saleform.cust">
                <el-option v-for="item in customers" :key="item.cust_id" :label="item.cust_name" :value="item.cust_id"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="销售日期" prop="date">
            <el-date-picker v-model="saleform.date" :value-format="dateFormat" type="datetimerange" range-separator="To" start-placeholder="Start date" end-placeholder="End date" style="width: 350px;" />
        </el-form-item>
        <el-form-item>
            <el-button @click="Reset">重置</el-button>
            <el-button type="success" @click="Search">查询</el-button>
            <el-button @click="AdvancedSearch">高级查询</el-button>
        </el-form-item>
    </el-form>
    <div style="text-align: left;">
        <el-button type="success" @click="ShowAdd">添加</el-button>
        <el-button type="danger" @click="ShowDeleteAll">删除</el-button>
        <el-button @click="ShowAudit">审核</el-button>
        <el-button @click="ShowCancelAll">撤销</el-button>
        <el-button @click="Export">导出</el-button>
        <el-button @click="Refresh">刷新</el-button>
    </div>
    <!--表格-->
    <el-table :data="saledata"  stripe style="margin-top: 10px;" @selection-change="SelectChange">
        <el-table-column fixed  type="selection"></el-table-column>
        <el-table-column fixed  type="index" label="序号" width="100"></el-table-column>
        <el-table-column fixed  label="销售单号" width="200px">
            <template #default="scope">
                <span style="color: green;cursor: pointer;" @click="ShowInfo(scope.row)">{{ scope.row.sale_code }}</span>
            </template>
        </el-table-column>
        <el-table-column fixed prop="sale_status" label="单据状态"></el-table-column>
        <el-table-column fixed prop="sale_date" label="销售日期" width="200px"></el-table-column>
        <el-table-column prop="cust_name" label="客户名称" width="200px"></el-table-column>
        <el-table-column prop="cust_linkman" label="联系人"></el-table-column>
        <el-table-column prop="cust_linkphone" label="联系方式" width="200px"></el-table-column>
        <el-table-column prop="sale_depName" label="销售部门" width="120px"></el-table-column>
        <el-table-column prop="sale_userName" label="销售负责人" width="120px"></el-table-column>
        <el-table-column prop="sale_num" label="销售数量"></el-table-column>
        <el-table-column prop="sale_total" label="销售金额" width="120px"></el-table-column>
        <el-table-column label="销售货品" width="300px">
            <template #default="scope">
                <el-tooltip
                    effect="dark"
                    :content="scope.row.proc_list_full"
                    placement="top"
                    :disabled="!scope.row.proc_list_full || scope.row.proc_list_full.split('、').length <= 3"
                >
                    <span>{{ scope.row.proc_list }}</span>
                </el-tooltip>
            </template>
        </el-table-column>
        <el-table-column prop="create_name" label="制单人"></el-table-column>
        <el-table-column prop="create_time" label="制单时间" width="200px"></el-table-column>
        <el-table-column prop="approver_name" label="审核人"></el-table-column>
        <el-table-column prop="approver_time" label="审核时间" width="200px"></el-table-column>
        <el-table-column label="操作" fixed="right" width="160px">
            <template #default="scope">
                <el-button 
                    v-if="['草稿', '待审核'].includes(scope.row.sale_status)"
                    type="success" 
                    text="编辑" @click="ShowUpdate(scope.row)">
                    编辑
                </el-button>
                <el-button 
                    v-if="['草稿', '待审核'].includes(scope.row.sale_status)"
                    type="danger" 
                    text="删除" @click="ShowDelete(scope.row.sale_id)">
                    删除
                </el-button>
                <el-button 
                    v-if="['未出库', '驳回'].includes(scope.row.sale_status)"
                    type="danger" 
                    text="撤销" @click="ShowCancel(scope.row.sale_id)">
                    撤销
                </el-button>
            </template>
        </el-table-column>
    </el-table>

     <!-- 页码 -->
    <el-pagination :page-size=10 :pager-count="11" layout="prev, pager, next,jumper" :total="rows"
        v-on:current-change="handlePageChange" style="float:right;margin-top:20px">
    </el-pagination>


    <!--高级查询-->
    <el-drawer v-model="drawer">
        <template #header>
            <h4 style="text-align: left;">高级查询</h4>
        </template>
        <template #default>
            <el-form label-width="120px" label-position="top" :model="searchform" ref="searchref">
                <el-row :gutter="24">
                    <!-- 左列 -->
                    <el-col :span="12">
                        <el-form-item label="销售单号" prop=code>
                            <el-input placeholder="请输入" v-model="searchform.code"/>
                        </el-form-item>
                        <el-form-item label="销售金额" prop="total">
                            <div style="display: flex; align-items: center;">
                                <el-input placeholder="请输入" v-model="searchform.starttotal" />
                                <span style="margin: 0 8px;">~</span>
                                <el-input placeholder="请输入" v-model="searchform.endtotal"/>
                            </div>
                        </el-form-item>
                        <el-form-item label="销售日期" prop="date">
                            <el-date-picker v-model="searchform.date" type="datetimerange" range-separator="To" start-placeholder="Start date" end-placeholder="End date" />
                        </el-form-item>
                        <el-form-item label="销售数量"  prop="num">
                            <div style="display: flex; align-items: center;">
                                <el-input placeholder="请输入" v-model="searchform.startnum"/>
                                <span style="margin: 0 8px;">~</span>
                                <el-input placeholder="请输入" v-model="searchform.endnum"/>
                            </div>
                        </el-form-item>
                        <el-form-item label="单据状态" prop="status">
                            <el-select placeholder="请选择" v-model="searchform.status">
                                <el-option v-for="item in status" :key="item.dict_value" :label="item.dict_label" :value="item.dict_value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="客户名称" prop="cust">
                            <el-select placeholder="请选择" v-model="searchform.cust">
                                <el-option v-for="item in customers" :key="item.cust_id" :label="item.cust_name" :value="item.cust_id"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="联系人" prop="custlink">
                            <el-input placeholder="请输入" v-model="searchform.custlink"/>
                        </el-form-item>
                    </el-col>
                    <!-- 右列 -->
                    <el-col :span="12">
                        <el-form-item label="销售部门" prop="dep">
                            <el-select placeholder="请选择" v-model="searchform.dep">
                                <el-option v-for="item in deps" :key="item.department_id" :label="item.department_name" :value="item.department_id"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="销售负责人" prop="user">
                            <el-select placeholder="请选择" v-model="searchform.user">
                                <el-option v-for="item in users" :key="item.user_id" :label="item.user_name" :value="item.user_id"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="制单人" prop="createname">
                            <el-input placeholder="请输入" v-model="searchform.createname"/>
                        </el-form-item>
                        <el-form-item label="制单时间" prop="createtime">
                            <el-date-picker v-model="searchform.createtime" type="datetimerange" range-separator="To" start-placeholder="Start date" end-placeholder="End date" />
                        </el-form-item>
                        <el-form-item label="审核人" prop="approvername">
                            <el-input placeholder="请输入" v-model="searchform.approvername"/>
                        </el-form-item>
                        <el-form-item label="审核时间" prop="approvertime">
                            <el-date-picker v-model="searchform.approvertime" type="datetimerange" range-separator="To" start-placeholder="Start date" end-placeholder="End date" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="AdvancedReset">重置</el-button>
                <el-button @click="drawer = false">关闭</el-button>
                <el-button type="primary" @click="AdvancedOk">确定</el-button>
            </div>
        </template>
    </el-drawer>

     <!--删除模态框-->
     <el-dialog v-model="DeleteialogVisible" width="400" style="text-align: left;"  align-center>
        <span>确定删除吗?</span>
        <template #footer>
            <div class="dialog-footer">
                <el-button v-on:click="DeleteialogVisible = false">取消</el-button>
                <el-button type="primary" @click="Delete()">确定</el-button>
            </div>
        </template>
    </el-dialog>

     <!--选中删除模态框-->
     <el-dialog v-model="DeleteialogVisible2" width="400" style="text-align: left;"  align-center>
        <span>确定删除选中的数据吗?</span>
        <template #footer>
            <div class="dialog-footer">
                <el-button v-on:click="DeleteialogVisible2 = false">取消</el-button>
                <el-button type="primary" @click="DeleteAll()">确定</el-button>
            </div>
        </template>
    </el-dialog>


    <!--撤销模态框-->
    <el-dialog v-model="CancelDialogVisible" width="400" style="text-align: left;"  align-center>
        <span>确定撤销吗?</span>
        <template #footer>
            <div class="dialog-footer">
                <el-button v-on:click="CancelDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="Cancel()">确定</el-button>
            </div>
        </template>
    </el-dialog>

    <!--选中撤销模态框-->
    <el-dialog v-model="CancelDialogVisible2" width="400" style="text-align: left;"  align-center>
        <span>确定撤销选中的数据吗?</span>
        <template #footer>
            <div class="dialog-footer">
                <el-button v-on:click="CancelDialogVisible2 = false">取消</el-button>
                <el-button type="primary" @click="CancelAll()">确定</el-button>
            </div>
        </template>
    </el-dialog>

    <!--审核模态框-->
    <el-dialog v-model="AuditDialogVisible" title="审核" width="400" style="text-align: left;" align-center>
        <div>
            <div style="margin-bottom: 15px;">
                <div>审核结果</div>
                <div style="margin-top: 10px;">
                    <el-radio v-model="auditResult" label="通过" style="margin-right: 20px;" value="7">通过</el-radio>
                    <el-radio v-model="auditResult" label="驳回" value="3">驳回</el-radio>
                </div>
            </div>
            <div>
                <div>审核意见</div>
                <el-input 
                    v-model="auditComment" 
                    type="textarea" 
                    rows="5" 
                    placeholder="请输入"
                    style="margin-top: 10px;"
                ></el-input>
            </div>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="AuditDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="Audit()">确定</el-button>
            </div>
        </template>
    </el-dialog>

</template>

<script>
import {ref,reactive,onMounted, computed} from 'vue';
import http from '../auth/index';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { useRouter } from 'vue-router';//路由
import * as XLSX from 'xlsx';
export default {
setup()
    {
        const router = useRouter();//路由
        //当前用户信息
        const user = JSON.parse(sessionStorage.getItem("user"));
        //日期转换格式
        function formatDateTime(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要+1
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }

        // 货品列表格式化函数
        function formatProductList(products) {
            if (!products) return "";
            
            // 如果是字符串先转为数组（如"三锅头、可笑、何必"）
            const productArray = Array.isArray(products) 
                ? products 
                : products.split('、').filter(Boolean);
            
            if (productArray.length <= 3) {
                return productArray.join('、');
            } else {
                const firstThree = productArray.slice(0, 3).join('、');
                return `${firstThree}等${productArray.length}项....`;
            }
        }

        //查询所有单据状态
        const status=ref([]);
        function GetStatus(){
            return http.get("/DictData/GetAllDictDataBytype?typeid=6")
            .then(res=>{
                status.value=res.data;
            }).catch(err=>{
                console.log(err);
            })
        }

        //查询所有客户
        const customers=ref([]);
        function GetCustomers(){
            return http.get("/Customer/GetCustomers")
            .then(res=>{
                customers.value=res.data;
            }).catch(err=>{
                console.log(err);
            })
        }

        //查询所有部门
        const deps=ref([]);
        function GetDepartments(){
            return http.get("/Department/GetDepartments")
            .then(res=>{
                deps.value=res.data;
            }).catch(err=>{
                console.log(err);
            })
        }

        //查询所有用户
        const users=ref([]);
        function GetUsers(){
            return http.get("/User/GetAllUser")
            .then(res=>{
                users.value=res.data;
            }).catch(err=>{
                console.log(err);
            })
        }

        const selectdata=ref([]);//选中数据
        //获取选中数据
        function SelectChange(val){
            selectdata.value=val;
        }

        //导出
        function Export(){
            if(selectdata.value.length==0){
                ElMessage({
                    message: '请选择要导出的数据.',
                    type: 'warning',
                })
                return;
            }
            // 创建工作簿
            const wb = XLSX.utils.book_new();
            // 准备数据
            const excelData = selectdata.value.map((row) => ({
                "销售单号": row.sale_code,
                "单据状态": row.sale_status,
                "销售日期": row.sale_date,
                "客户名称": row.cust_name,
                "联系人": row.cust_linkman,
                "联系方式": row.cust_linkphone,
                "销售部门": row.sale_depName,
                "销售负责人": row.sale_userName,
                "销售数量": row.sale_num,
                "销售金额": row.sale_total,
                "销售货品": row.proc_list,
                "制单人": row.create_name,
                "制单时间": row.create_time,
                "审核人": row.approver_name,
                "审核时间": row.approver_time
            }));
            // 创建工作表
            const ws = XLSX.utils.json_to_sheet(excelData);
            // 添加到工作簿
            XLSX.utils.book_append_sheet(wb, ws, "销售单");
            // 导出并下载
            XLSX.writeFile(wb, `销售单${new Date().toLocaleDateString()}.xlsx`);
        }

        //当前销售单id
        const saleid=ref("");


        //刷新
        function Refresh(){
            All();
        }
        

        //#region 查询
        
        const saleref=ref("");
        const saleform=reactive({
            code:"",
            ordstatus:"",
            cust:"",
            date:[null,null]
        })

        function Reset(){
            saleref.value?.resetFields();
            All();
        }

        //表格数据
        const saledata = ref([]);
        //总数据量
        const rows = ref(0);
        //当前页
        const currentPage = ref(1);
        //日期格式
        const dateFormat = 'YYYY-MM-DD HH:mm:ss';

        // 状态映射计算属性
        const statusMap = computed(() => {
            const map = {};
            if (status.value && status.value.length > 0) {
                status.value.forEach(item => {
                    map[item.dict_value] = item.dict_label;
                });
            }
            return map;
        });

        //查询
        function Search() {
            All();
        }

        //查询数据
        function All(){
        
            http.get("/Sale_h/GetSale_h", {
                params: {
                    code: saleform.code,
                    status: saleform.ordstatus,
                    cust:saleform.cust,
                    starttime:saleform.date[0],
                    endtime:saleform.date[1],
                    CurrentPage: currentPage.value
                }
            }).then(res => {
                rows.value = res.data.rows;//总量
                if (res.data.list.length == 0) {
                    ElMessage({
                        message: '没有相关数据.',
                        type: 'warning',
                    })
                }
                //数据转换
                const Data = res.data.list.map(item => ({
                    ...item, // 复制原始对象的所有属性
                    sale_date: formatDateTime(new Date(item.sale_date)),
                    create_time: formatDateTime(new Date(item.create_time)),
                    approver_time: item.approver_time ? formatDateTime(new Date(item.approver_time)) : "",
                    sale_total: item.sale_total ? Number(item.sale_total).toFixed(2) : "0.00",
                    proc_list_full: item.proc_list,
                    proc_list: formatProductList(item.proc_list),
                    sale_status: statusMap.value[item.sale_status] || "未知状态",
                }));

                // 按照创建时间降序排序
                Data.sort((a, b) => new Date(b.create_time) - new Date(a.create_time));

                saledata.value = Data;
            }).catch(err => {
                console.log(err)
            })
        }

        //改变页数
        function handlePageChange(page) {
            currentPage.value = page
            All();
        }


        //#endregion


        //#region 高级查询
        const drawer=ref(false);
        function AdvancedSearch(){
            drawer.value=true
        }
        const searchref=ref("");
        const searchform=reactive({
            code:"",
            total:"",
            starttotal:"",
            endtotal:"",
            date:[null,null],
            num:"",
            startnum:"",
            endnum:"",
            status:"",
            cust:"",
            custlink:"",
            dep:"",
            user:"",
            createname:"",
            createtime:[null,null],
            approvername:"",
            approvertime:[null,null]
        })

         //重置
         function AdvancedReset(){
            searchref.value?.resetFields();
            searchform.starttotal="",
            searchform.endtotal="",
            searchform.startnum="",
            searchform.endnum=""
        }


        function AdvancedOk(){
            http.get("/Sale_h/GetAdvancedSale_h",{
                params:{
                    code:searchform.code,
                    starttotal:searchform.starttotal,
                    endtotal:searchform.endtotal,
                    startdate:searchform.date[0],
                    enddate:searchform.date[1],
                    startnum:searchform.startnum,
                    endnum:searchform.endnum,
                    status:searchform.status,
                    cust:searchform.cust,
                    custlink:searchform.custlink,
                    dep:searchform.dep,
                    user:searchform.user,
                    createname:searchform.createname,
                    startcreatetime:searchform.createtime[0],
                    endcreatetime:searchform.createtime[1],
                    approvername:searchform.approvername,
                    startapprovertime:searchform.approvertime[0],
                    endapprovertime:searchform.approvertime[1],
                    CurrentPage:currentPage.value
                }
            }).then(res => {
                rows.value = res.data.rows;//总量
                if (res.data.list.length == 0) {
                    ElMessage({
                        message: '没有相关数据.',
                        type: 'warning',
                    })
                }
                //数据转换
                const Data = res.data.list.map(item => ({
                    ...item, // 复制原始对象的所有属性
                    sale_date: formatDateTime(new Date(item.sale_date)),
                    create_time: formatDateTime(new Date(item.create_time)),
                    approver_time: item.approver_time ? formatDateTime(new Date(item.approver_time)) : "",
                    sale_total: item.sale_total ? Number(item.sale_total).toFixed(2) : "0.00",
                    proc_list_full: item.proc_list,
                    proc_list: formatProductList(item.proc_list),
                    sale_status: statusMap.value[item.sale_status] || "未知状态",
                }));

                // 按照创建时间降序排序
                Data.sort((a, b) => new Date(b.create_time) - new Date(a.create_time));

                saledata.value = Data;
            }).catch(err => {
                console.log(err)
            })
        }

        //#endregion

        //#region 跳转到新增界面
        function ShowAdd(){
            router.push("saleadd");
        }
        //#endregion

        //#region 删除

            //删除模态框
            const DeleteialogVisible=ref(false);
            //删除模态框
            function ShowDelete(id){
                saleid.value=id;
                DeleteialogVisible.value=true;
            }
            async function Delete(){
                try {
                    // 1. 根据 saleid 获取销售明细
                    const detailRes = await http.get("/Sale_d/GetSale_ds?saleid=" + saleid.value);
                    const details = detailRes.data;

                    // 2. 遍历明细，将数量加回库存
                    for (const item of details) {
                        const productRes = await http.get(`/Product/GetProductById?id=${item.proc_id}`);
                        const product = productRes.data;
                        if (product) {
                            const newInventory = (product.proc_ky_inventory || 0) + (item.proc_saled_num || 0);
                            await http.put(`/Product/Updateky?id=${item.proc_id}&inventory=${newInventory}`);
                        }
                    }

                    // 3. 删除销售单
                    const deleteRes = await http.put("/Sale_h/DeleteSale_h?id=" + saleid.value);
                    if (deleteRes.data > 0) {
                        ElMessage({
                            message: '删除成功，库存已退回.',
                            type: 'success',
                        });
                        All(); // 刷新列表
                        DeleteialogVisible.value = false;
                    } else {
                        ElMessage.error('删除失败.');
                    }
                } catch (err) {
                    console.error("删除失败:", err);
                    ElMessage.error('删除操作失败.');
                }
            }

            const DeleteialogVisible2=ref(false);
            function ShowDeleteAll(){
                if(selectdata.value.length==0){
                    ElMessage({
                        message: '请选择要删除的数据.',
                        type: 'warning',
                    })
                    return;
                }

                // 检查选中的单据是否都可删除
                const invalidItems = selectdata.value.filter(item => 
                    !['草稿', '待审核'].includes(item.sale_status)
                );

                if (invalidItems.length > 0) {
                    ElMessage({
                        message: '选中的单据中包含不可删除的状态(只有草稿或待审核状态可删除)',
                        type: 'warning',
                    });
                    return;
                }

                DeleteialogVisible2.value=true;
            }

            //批量删除
            async function DeleteAll(){
                try {
                    for (const row of selectdata.value) {
                        const detailRes = await http.get("/Sale_d/GetSale_ds?saleid=" + row.sale_id);
                        const details = detailRes.data;

                        for (const item of details) {
                            const productRes = await http.get(`/Product/GetProductById?id=${item.proc_id}`);
                            const product = productRes.data;
                            if (product) {
                                const newInventory = (product.proc_ky_inventory || 0) + (item.proc_saled_num || 0);
                                await http.put(`/Product/Updateky?id=${item.proc_id}&inventory=${newInventory}`);
                            }
                        }
                        await http.put("/Sale_h/DeleteSale_h?id=" + row.sale_id);
                    }

                    ElMessage({
                        message: '选中单据删除成功，库存已退回.',
                        type: 'success',
                    });
                    All(); // 刷新列表
                    DeleteialogVisible2.value = false;

                } catch (err) {
                    console.error("批量删除失败:", err);
                    ElMessage.error('批量删除操作失败.');
                }
            }


        //#endregion

        //#region 跳转到修改页面
        function ShowUpdate(row){
            router.push({
                name:"saleupdate",
                params:{
                    saleid:row.sale_id,
                    salecode:row.sale_code
                }
            })
        }
        
        //#endregion

        //#region 撤销
        //当单据状态为，未入库且驳回的状态时可以撤销（待审核）
        const CancelDialogVisible=ref(false);
        function ShowCancel(id){
            saleid.value=id;
            CancelDialogVisible.value=true;
        }
        //撤销
        function Cancel(){
            http.put("/Sale_h/UpdateStatus?saleid="+saleid.value+"&status=2")
            .then(res=>{
                if(res.data>0){
                    ElMessage({
                        message: '撤销成功.',
                        type: 'success',
                    })
                    All();
                    CancelDialogVisible.value=false;
                }else{
                    ElMessage.error('撤销失败.')
                }
            }).catch(err=>{
                console.log(err);
            })
        }
        
        //选中撤销
        const CancelDialogVisible2=ref(false);
        function ShowCancelAll() {
            if(selectdata.value.length === 0) {
                ElMessage({
                    message: '请选择要撤销的单据.',
                    type: 'warning',
                });
                return;
            }
            
            // 检查是否有可撤销的单据
            const validItems = selectdata.value.filter(item => 
                item.sale_status === "未出库" || item.sale_status === "驳回");
            
            if (validItems.length === 0) {
                ElMessage({
                    message: '选中的单据中没有可撤销的单据(只有未出库或驳回状态可撤销)',
                    type: 'warning',
                });
                return;
            }
            
            CancelDialogVisible2.value = true;
        }
        //批量撤销
        function CancelAll(){
            selectdata.value.forEach(item => {
                if(item.sale_status === "未出库" || item.sale_status === "驳回"){
                    http.put("/Sale_h/UpdateStatus?saleid="+item.sale_id+"&status=2")
                    .then(res=>{
                        if(res.data>0){
                            ElMessage({
                                message: '撤销成功.',
                                type: 'success',
                            })
                            All();
                            CancelDialogVisible2.value=false;
                        }else{
                            ElMessage.error('撤销失败.')
                        }
                    }).catch(err=>{
                        console.log(err);
                    })
                }
            })
        }
        //#endregion

        //#region 审核
        //审核模态框
        const AuditDialogVisible=ref(false);
        const auditResult=ref("3");
        const auditComment=ref("");
        function ShowAudit(){
            if(selectdata.value.length==0){
                ElMessage({
                    message: '请选择要审核的单据.',
                    type: 'warning',
                })
                return;
            }
            //检查是否有可审核的单据
            const validItems = selectdata.value.filter(item => 
                item.sale_status === "待审核");
            if(validItems.length==0){
                ElMessage({
                    message: '选中的单据中没有可审核的单据(只有待审核状态可审核)',
                    type: 'warning',
                })
                return;
            }
            AuditDialogVisible.value=true;
        }

        function Audit(){
            selectdata.value.forEach(item => {
                if(item.sale_status === "待审核"){
                    http.put("/Sale_h/ApproverSale_h?saleid="+item.sale_id+"&status="+auditResult.value+"&approvername="+user.name+"&approvertime="+formatDateTime(new Date()))
                    .then(res=>{
                        if(res.data>0){
                            ElMessage({
                                message: '审核成功.',
                                type: 'success',
                            })
                            All();
                            AuditDialogVisible.value=false;
                        }else{
                            ElMessage.error('审核失败.')
                        }
                    }).catch(err=>{
                        console.log(err);
                    })
                }
            })
        }
        //#endregion


        //#region 查看详情信息
        function ShowInfo(row){
            router.push({
                name:"saleinfo",
                params:{
                    saleid:row.sale_id,
                    salecode:row.sale_code
                }
            })
        }

        //挂载
        onMounted(() => {
            // 先加载状态数据，然后再加载其他数据
            GetStatus().then(() => {
                // 状态数据加载完成后，再执行查询
                All();
            });
            // 同时加载其他数据
            GetCustomers();
            GetDepartments();
            GetUsers();
        });

        return{
            AdvancedSearch,
            drawer,
            status,
            saleref,
            saleform,
            Reset,
            customers,
            saledata,
            rows,
            currentPage,
            dateFormat,
            handlePageChange,
            Search,
            searchform,
            searchref,
            AdvancedReset,
            AdvancedOk,
            deps,
            users,
            ShowAdd,
            selectdata,
            SelectChange,
            Export,
            DeleteialogVisible,
            ShowDelete,
            Delete,
            saleid,
            DeleteAll,
            DeleteialogVisible2,
            ShowDeleteAll,
            ShowUpdate,
            ShowCancel,
            CancelDialogVisible,
            Cancel,
            CancelDialogVisible2,
            ShowCancelAll,
            CancelAll,
            AuditDialogVisible,
            auditResult,
            auditComment,
            ShowAudit,
            Audit,
            Refresh,
            ShowInfo
        }
    }
}
</script>

<style scoped>

</style>